var express = require('express');
var router = express.Router();
var User = require('../models/user.js');
var Custom = require('../models/custom.js');
var Article = require('../models/article.js');


/* GET 登陆 page. */
router.get('/login', checkNotLogin);
router.get('/login', function (req, res, next) {
    res.render('login', {
        title: '登陆页',
        user: req.session.user
    });
});

//router.post('/login', checkNotLogin);
router.post('/login', function (req, res) {

    //生成密码的md5值
    var password = req.body.password;
    //检查用户是否存在
    User.get(req.body.name, function (err, user) {

        if (!user) {
            return res.send({
                isChecked: false,
                text: '用户不存在'
            });
        }

        //检查密码是否一致
        if (user.password != password) {

            return res.send({
                isChecked: false,
                text: '密码错误'
            });
        }

        //用户名密码都匹配，用户信息存入session
        req.session.user = user;

        res.send({
            isChecked: true
        });

    });
});
/*注册页面*/
// router.get('/regist', function(req, res) {
//     res.render('regist',{
//         title: '注册页',
//         user: req.session.user
//     });
// });

// router.post('/regist', function(req, res) {

//     var newUser = new User({
//         name: req.body.name,
//         password: req.body.password
//     });

//     User.get(newUser.name, function(err, user) {
//         if (err) {
//             return res.redirect('/');
//         }
//         if (user) {
//             return res.redirect('/regist'); //返回注册页
//         }
//         //如果不存在则新增用户
//         newUser.save(function(err, user) {
//             if (err) {
//                 return res.redirect('/regist'); //注册失败返回主册页
//             }
//             req.session.user = user; //用户信息存入 session
//             res.redirect('/'); //注册成功后返回主页
//         });
//     });

// });
/* GET 首页 page. */

router.get('/', checkLogin);

router.get('/', function (req, res, next) {
    res.render('index',
        {
            iframeUrl: '/cusorigin',
            leftbar: 'dataleft' //这一步还没有实现传参数
        });
});

/*数据来源*/
router.get('/cusorigin', function (req, res, next) {
    var alcustomer = 0;
    var alsecretary = 0;
    var alminnet = 0;
    var alline = 0;
    var allother = 0;
    var tcustomer = 0;
    var tsecretary = 0;
    var tminnet = 0;
    var tline = 0;
    var tother = 0;
    var time = new Date();
    var month = time.getMonth() + 1;
    var day = time.getDate();
    var newmonth = initTime(month);
    var newday = initTime(day);

    function initTime(time) {
        if (time >= 10) {
            return time;
        }
        else if (time < 10) {
            var newtime = '0' + time;
            return newtime;
        }
    };
    var today = time.getFullYear() + '-' + newmonth + '-' + newday;
    Custom.get(function (err, customs) {
        if (err) {
            return res.redirect('/cus/all');
        }
        for (var i = 0, len = customs.length; i < len; i++) {
            if (customs[i].type == '客带客') {
                alcustomer++;
                if (customs[i].time == today) {
                    tcustomer++;
                }
            }
            else if (customs[i].type == '小秘书') {
                alsecretary++;
                if (customs[i].time == today) {
                    tsecretary++;
                }
            }
            else if (customs[i].type == '微官网') {
                alminnet++;
                if (customs[i].time == today) {
                    tminnet++;
                }
            }
            else if (customs[i].type == '线下营销') {
                alline++;
                if (customs[i].time == today) {
                    tline++;
                }
            }
            else if (customs[i].type == '其他') {
                allother++;
                if (customs[i].time == today) {
                    tother++;
                }
            }
        }
        var totalall = alcustomer + alsecretary + alminnet + alline + allother;
        var totalt = tcustomer + tsecretary + tminnet + tline + tother;

        res.render('cusorigin', {
            alcustomer: alcustomer,
            alsecretary: alsecretary,
            alminnet: alminnet,
            alline: alline,
            allother: allother,

            tcustomer: tcustomer,
            tsecretary: tsecretary,
            tminnet: tminnet,
            tline: tline,
            tother: tother,
            totalt: totalt,
            totalall: totalall,
            orgother: 208 - allother,
            orgline: 208 - alline,
            orgminnet: 208 - alminnet,
            orgsecretary: 208 - alsecretary,
            orgcustomer: 208 - alcustomer
        });
    });
});

/*添加客户*/
router.post('/custom', function (req, res) {
    var shareMobile = req.body.shareMobile;
    var parent = {};
    Custom.getParent(shareMobile, function (err, customs) {
        if (err) {
            return res.redirect('/cus/all');
        }
        parentId = customs[0]._id;

        var custom = new Custom({
            mobile: req.body.mobile,
            remarkName: req.body.remarkName,
            password: req.body.password,
            type: req.body.type,
            time: req.body.time,
            consultantId: req.body.consultantId,
            shareMobile: req.body.shareMobile,
            parentId: parentId
        });
        custom.save(function (err, custom) {
            if (err) {
                return res.redirect('/cus/all'); //注册失败返回主册页
            }
            req.session.custom = custom; //用户信息存入 session
            res.redirect('/cus/all'); //注册成功后返回主页
        });
    });

});
/*手机*/
//手机注册添加客户
router.post('/addphonecustom', function (req, res) {
    var shareMobile = req.body.shareMobile;
    var parent = {};
    Custom.getParent(shareMobile, function (err, customs) {
        if (err) {
            return res.redirect('userRegist');
            // console.log(err);
        }
        parentId = customs[0]._id;

        var custom = new Custom({
            mobile: req.body.mobile,
            remarkName: req.body.name,
            shareMobile: req.body.shareMobile,
            password: req.body.password,
            consultantId: req.body.consultantId,
            parentId: parentId
        });
        custom.save(function (err, custom) {
            if (err) {
                return res.redirect('/'); //注册失败返回主册页
            }

            res.redirect('/userLogin'); //注册成功后返回主页
        });
    });

});
//手机注册页面
router.get('/userRegist', function (req, res, next) {
    res.render('userRegist');
});
/*手机登陆*/
router.post('/PuserLogin', function (req, res) {
    var mobile = req.body.account;
    var password = req.body.password;
    Custom.userLogin(mobile, function (err, custom) {
        if (err) {
            res.redirect('/userLogin');
        }
        else if (custom.password != password) {
            return res.send({
                msg: '密码错误'
            })
        }
        else if (custom.password == password) {
            req.session.custom = custom;
            return res.send({
                msg: 'success'
            })
        }
    });
});
/*test页面获取session*/

router.get('/userlogin', function (req, res, next) {
    res.render('userLogin');
})
/*会所概况页面*/
router.get('/intro', function (req, res) {
    res.render('introduce');

});
/*phone页面*/
router.get('/phone', function (req, res) {
    res.render('phone');
});
/*俱乐部风采面*/
router.get('/pic', function (req, res) {
    res.render('picture');
});
/*用户中心*/
router.get('/user', function (req, res) {
    res.render('user');
});
/*用户登录*/
/*router.get('/userLogin', function (req, res) {
 res.render('userLogin');
 });*/

/*用户注册*/
router.get('/userRegist', function (req, res) {
    res.render('userRegist');
});
/*我影响的客户*/
router.get('/myinflu', function (req, res, next) {
    //var  childs = [];                                                                                                                                                                                                                                                                                                                                                                                                                                                          ;
    Custom.getchilds(req.session.custom._id, function (err, childs) {
        if (err) {
            console.log(err);
        }
        res.render('myinflu', {

            childs: childs,
            all: childs.length
        });
    });
})
/*用户登录成功*/
router.get('/isLogin', function (req, res) {
    res.render('isLogin');
})
/*新闻*/

router.get('/news', function (req, res, next) {
    Article.getAll(function (err, articles) {

        if (err) {
            return res.redirect('back');
        }
        res.render('news', {
            articles: articles
        });
    });

});
/*新闻详细页*/

router.get('/news_content/:_id', function (req, res) {
    Article.getOneMessage(req.params._id, function (err, article) {
        if (err) {
            console.log(err);
        }
        res.render('news_content', {
            article: article
        });
    });
});

router.get('/addNews', function (req, res, next) {
    res.render('news/addnews');
});

router.post('/addNews', function (req, res, next) {
    var article = new Article(req.body.title, req.body.text);

    article.save(function (err) {
        if (err) {
            return res.redirect('back');
        }

        return res.redirect('/newsList');
    });
});

router.get('/updateArticle/:_id', function (req, res, next) {

    Article.getOneMessage(req.params._id, function (err, article) {
        res.render('news/updatenews', {
            article: article
        });
    });

});


router.post('/updateArticle', function (req, res, next) {
    Article.update(req.body._id, req.body.title, req.body.text, function (err) {

        if (err) {
            return res.redirect('back');
        }

        return res.redirect('/newsList');

    });
});

router.get('/removeOneArticle/:_id', function (req, res, next) {

    Article.removeOne(req.params._id, function (err, article) {

        return res.redirect('back');

    });

});

router.get('/newsList', function (req, res, next) {
    Article.getAll(function (err, articles) {

        if (err) {
            return res.redirect('back');
        }

        res.render('news/newsList', {
            articles: articles
        });

    });

});

router.get('/newsindex', function (req, res, next) {
    res.render('news/newsindex', {iframeUrl: '/newsList'});
});

/*客户列表页*/
router.get('/cus/all', function (req, res) {
    var query = {};
    var page = req.query.page ? parseInt(req.query.page) : 1;
    Custom.getTenCustom(query, page, function (err, custom, total) {
        if (err) {
            return res.redirect('/cus/all');
        }
        res.render('allcustomerlist', {
            query: query,
            newdata: custom,
            page: page,
            isFirstPage: (page - 1) == 0,
            isLastPage: ((page - 1) * 10 + custom.length) == total,
            total: total
        });
    });
});

/* GET customermanage page. */
router.get('/cus', function (req, res, next) {
    res.render('cusindex', {iframeUrl: '/cus/all'});
});

/*客户详情*/
router.get('/cus/detail/:_id', function (req, res, next) {
    Custom.getOneMessage(req.params._id, function (err, custom) {
        if (err) {
            console.log(err);
        }
        res.render('cusdetail', {
            mydata: custom
        });
    });
});
/*删除*/
router.get('/removeOne/:_id', function (req, res) {
    Custom.delete(req.params._id, function (err) {
        if (err) {
            req.flash('error', err);

        }
        return res.redirect('back');
    });

});
/*影响客户*/
router.get('/influence/:_id', function (req, res, next) {

    Custom.getOneMessage(req.params._id, function (err, custom) {
        if (err) {
            console.log(err);
        }
        var custom = custom;
        //var  childs = [];                                                                                                                                                                                                                                                                                                                                                                                                                                                          ;
        Custom.getchilds(req.params._id, function (err, childs) {
            if (err) {
                console.log(err);
            }
            res.render('influence', {
                mydata: custom,
                newdata: childs
            });
        });
    });
});

/*营销工具*/
router.get('/selltool', function (req, res, next) {
    res.render('selltool/selltoolindex', {iframeUrl: '/selltool/sellArtlist'});
});

router.get('/selltool/sellArtlist', function (req, res, next) {
    res.render('selltool/softArcticalList', {toUrl: '/selltool/allArt'});
});

router.get('/selltool/allArt', function (req, res, next) {
    res.render('selltool/addAritical', {iframeUrl: ''});
});
/*注册与邀请好友*/
router.get('/selltool/friend', function (req, res, next) {
    res.render('selltool/friend');
});


/*账号管理*/
// /*角色管理主页*/
router.get('/role', function (req, res, next) {
    res.render('role/roleindex', {iframeUrl: '/regist'});
});
// /*账户管理*/
// router.get('/role/account', function(req, res, next) {
//   res.render('role/account');
// });
// router.get('/role/rolemange', function(req, res, next) {
//   res.render('role/rolemanage');
// });

router.get('/regist', function (req, res) {

    User.getAll(function (err, users) {

        if (err) {
            return res.redirect('back');
        }

        res.render('role/account', {
            users: users
        });

    });

});

router.get('/removeOneuser/:_id', function (req, res, next) {

    User.removeOne(req.params._id, function (err, article) {

        return res.redirect('back');

    });

});
router.post('/regist', function (req, res) {

    var newUser = new User({
        name: req.body.name,
        password: req.body.password
    });

    User.get(newUser.name, function (err, user) {
        if (err) {
            return res.redirect('/regist');
        }
        if (user) {
            return res.redirect('/regist'); //返回注册页
        }
        //如果不存在则新增用户
        newUser.save(function (err, user) {
            if (err) {
                return res.redirect('/regist'); //注册失败返回主册页
            }

            res.redirect('/regist'); //注册成功后返回主页
        });
    });

});
/*检查是否登陆*/
function checkLogin(req, res, next) {

    if (!req.session.user) {
        res.redirect('/login');
    }

    next();

}

function checkNotLogin(req, res, next) {

    if (req.session.user) {
        return res.redirect('back');// 返回之前的页面
    }

    next();

}
module.exports = router;
